<!DOCTYPE html>
<html lang="en">

<head>
  <title>Home Assistant</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,user-scalable=no" />
  <link href="assets/style.css" rel="stylesheet" />
  <link href="assets/checkmark.css" rel="stylesheet" />
  <script>
    const { ipcRenderer } = require('electron');
    const Bonjour = require('bonjour-service');
    const bonjour = new Bonjour.Bonjour();

    function showInstance(url) {
      if (url === '') {
        return;
      }

      document.getElementById('availableInstancesContainer').style.display = 'block';
      const button = document.createElement('button');
      button.onclick = () => addInstance(url);
      button.classList.add('pure-material-button-contained');
      button.textContent = url;
      document.getElementById('availableInstances').append(button);
    }

    document.addEventListener('DOMContentLoaded', function () {
      setTimeout(() => document.getElementById('url').focus(), 300);
    });

    ipcRenderer.send('get-instances');
    ipcRenderer.on('get-instances', (event, result) => {
      let instances = result;

      bonjour.find({type: 'home-assistant'}, instance => {
        if (instance.txt.internal_url && instances.indexOf(instance.txt.internal_url) === -1) {
          showInstance(instance.txt.internal_url);
        }

        if (instance.txt.external_url && instances.indexOf(instance.txt.external_url) === -1) {
          showInstance(instance.txt.external_url);
        }
      })
    })

    function addInstance(url) {
      const urlField = document.getElementById('url');
      urlField.value = url;
      checkUrl();
    }

    function saveInstance() {
      const urlField = document.getElementById('url');
      document.getElementById('check-wrapper').style.display = 'block';
      document.getElementById('url-wrapper').style.display = 'none';
      showCheckmark = true;
      ipcRenderer.send('ha-instance', urlField.value);
    }

    ipcRenderer.send('ha-instance');

    let showCheckmark = false;

    ipcRenderer.on('ha-instance', function (event, url) {
      if (showCheckmark) {
        document
          .getElementById('check-wrapper')
          .addEventListener(
            'animationend',
            () => (window.location.href = url)
          );
      } else {
        window.location.href = url;
      }
    });

    function isValidUrl(string) {
      try {
        new URL(string);
      } catch (_) {
        return false;
      }

      return true;
    }

    function checkUrl() {
      const urlField = document.getElementById('url');
      const submitBtn = document.getElementById('submit');
      submitBtn.disabled = true;
      let url = urlField.value;
      urlField.classList.remove('is-invalid', 'is-valid');

      if (!url.startsWith('http') || !isValidUrl(url)) {
        urlField.classList.add('is-invalid');
        return;
      }

      url = new URL(url);

      if (url.pathname.length > 1 && !url.pathname.startsWith('/lovelace') && !url.pathname.startsWith('/energy')) {
        console.log(url.pathname, !url.pathname.startsWith('/lovelace'));
        urlField.classList.add('is-invalid');
        return;
      }

      urlField.classList.add('is-valid');

      fetch(`${url.origin}/auth/providers`)
        .then(response => response.text())
        .then(data => {
          if (!data.includes('homeassistant')) {
            return;
          }

          submitBtn.disabled = false;
        }).catch((_) => {
      });
    }
  </script>
</head>

<body>
<div class="container">
  <div class="content">
    <div class="center header">
      <img src="assets/favicon.png" height="52"/> Home Assistant
    </div>
    <div id="availableInstancesContainer" style="display:none;">
      <div class="center">
        <p>Available Instances: </p>
      </div>
      <div class="center">
        <div id="availableInstances">
        </div>
      </div>
    </div>
    <div class="center" style="margin-top: 30px;">

    </div>
    <div class="center">
      <div id="check-wrapper" class="success-checkmark">
        <div class="check-icon center">
          <span class="icon-line line-tip"></span>
          <span class="icon-line line-long"></span>
          <div class="icon-circle"></div>
          <div class="icon-fix"></div>
        </div>
        <p>
          <small class="grey">Your URL is checked, and you will be forwarded to Home Assistant automatically.</small>
        </p>
      </div>

      <div id="url-wrapper" class="group">
        <input type="url" required="required" id="url" placeholder="e.g. http://homeassistant.local:8123" onkeyup="checkUrl()" />
        <span class="highlight"></span>
        <span class="bar"></span>
        <label for="url">Home Assistant URL</label>
        <div class="invalid-feedback">Please provide a valid url.</div>
        <button class="pure-material-button-contained" id="submit" onclick="saveInstance()" disabled>Submit</button>
      </div>
    </div>
  </div>
</div>
</body>

</html>
